<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDept, deleteDeptList, getDeptTree } from '#/api/system/dept';
import { $t } from '#/locales';

import { useGridColumns } from './data';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function handleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 创建部门 */
function handleCreate() {
  formDrawerApi.setData(null).open();
}

/** 添加下级部门 */
function handleAppend(row: SystemDeptApi.Dept) {
  formDrawerApi.setData({ parentId: row.id }).open();
}

/** 编辑部门 */
function handleEdit(row: SystemDeptApi.Dept) {
  formDrawerApi.setData(row).open();
}

/** 删除部门 */
async function handleDelete(row: SystemDeptApi.Dept) {
  try {
    await ElMessageBox.confirm(
      $t('ui.actionMessage.deleteConfirm', [row.name]),
      $t('common.tips'),
      {
        type: 'warning',
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
      },
    );

    const loading = ElLoading.service({
      lock: true,
      text: $t('ui.actionMessage.deleting', [row.name]),
    });

    try {
      await deleteDept(row.id!);
      ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
      handleRefresh();
    } finally {
      loading.close();
    }
  } catch {
    // 用户取消删除
  }
}

/** 批量删除部门 */
async function handleDeleteBatch() {
  try {
    await ElMessageBox.confirm(
      $t('ui.actionMessage.deleteBatchConfirm', [$t('system.dept.name')]),
      $t('common.tips'),
      {
        type: 'warning',
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
      },
    );

    const loading = ElLoading.service({
      lock: true,
      text: $t('ui.actionMessage.deletingBatch', [$t('system.dept.name')]),
    });

    try {
      await deleteDeptList(checkedIds.value);
      checkedIds.value = [];
      ElMessage.success($t('ui.actionMessage.deleteSuccess'));
      handleRefresh();
    } finally {
      loading.close();
    }
  } catch {
    // 用户取消删除
  }
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemDeptApi.Dept[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    // stripe: true, // 显示分隔符
    // border: true, // 显示边框
    columns: useGridColumns(onActionClick),
    height: 'auto',
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async () => {
          return await getDeptTree();
        },
      },
    },
    showOverflow: true,

    checkboxConfig: {
      labelField: 'name',
      checkStrictly: true,
      showHeader: true,
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: true,
      zoom: true,
    },
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: false,
      expandAll: true,
      reserve: true,
    },
  } as VxeTableGridOptions<SystemDeptApi.Dept>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<SystemDeptApi.Dept>) {
  switch (code) {
    case 'append': {
      handleAppend(row);
      break;
    }
    case 'delete': {
      handleDelete(row);
      break;
    }
    case 'edit': {
      handleEdit(row);
      break;
    }
  }
}
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="handleRefresh" />
    <Grid table-title="部门列表">
      <template #toolbar-tools>
        <ElButton type="primary" @click="handleCreate"> 新增 </ElButton>

        <ElButton type="primary" @click="handleExpand">
          {{ isExpanded ? '折叠' : '展开  ' }}
        </ElButton>

        <ElButton
          type="danger"
          @click="handleDeleteBatch"
          :disabled="isEmpty(checkedIds)"
        >
          批量删除
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
